package abel.wlmr.model.type;

import abel.wlmr.model.WlmrException;
import abel.wlmr.model.WlmrField;

/**
 * Default to 3, which means 1bar.
 * 0110 10nn 压力 10（nn-3)bar 0.001 bar ～ 1bar
 * 
 * @author Abel
 *
 */
public class PressUnitField extends WlmrField {
    private static final int prefix = 0x68;

    /**
     * Default to 3, which means 1bar.
     */
    private byte nn = 3;

    public PressUnitField() {
        super(1);
    }

    @Override
    public int getValue() {
        return prefix | nn;
    }

    @Override
    public void parseValue(int v) throws WlmrException {
        byte key = (byte) (v & 0xFC);
        if (key != prefix) {
            throw new WlmrException("pressure unit is invalid: " + v);
        }

        nn = (byte) (v & 0x03);
    }

    /** return base value in readable format. */
    public double baseValue() {
        return Math.pow(10, nn - 3);
    }

    /**
     * Default to 3, which means 1bar.
     * return base unit in readable format.
     */
    public String baseUnit() {
        return "bar";
    }

    /**
     * Default to 3, which means 1bar.
     * 
     * @return the nn
     */
    public byte getNn() {
        return nn;
    }

    /**
     * Default to 3, which means 1bar.
     * 
     * @param nn
     *            the nn to set
     */
    public void setNn(byte nn) {
        if (nn < 0 || nn > 3) {
            throw new IllegalArgumentException("nn should be [0,3]");
        }

        this.nn = nn;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("PressUnit [nn=%s, baseValue()=%s, baseUnit()=%s]", nn, baseValue(), baseUnit());
    }

}
